// ==UserScript==
// @name         spotifyPlayListExtracter
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include       https://open.spotify.com/*
// @grant        none
// ==/UserScript==

(function () {
  "use strict";

  let trackArray = [];

  const copyToClipboard = str => {
    const el = document.createElement("textarea");
    el.value = str;
    el.setAttribute("readonly", "");
    el.style.position = "absolute";
    el.style.left = "-9999px";
    document.body.appendChild(el);
    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);
  };

  const timer = setTimeout(action, 3000); // wait for the page to stay still for 3 seconds

  function action() {
    const playlistBtnWrapper = document.querySelector(
      ".TrackListHeader__button"
    );
    playlistBtnWrapper.insertAdjacentHTML(
      "beforeend",
      '<button id="copyListItem" class="btn btn-green false" style="margin-left:15px;">COPY</button>'
    );

    document.getElementById("copyListItem").onclick = function () {
      if (trackArray.length > 0) {
        trackArray = [];
      }

      let tracks = document.querySelectorAll(".tracklist .tracklist-row");

      tracks.forEach((v, i, a) => {
        let trackObj = {};

        trackObj.title = v.querySelector('.name .tracklist-name').innerText;

        let trackMetaInfoNodes = v.querySelectorAll('.name .second-line > span');

        let artistNames = [];
        if (trackMetaInfoNodes.length === 3) {
          let artistNodes = trackMetaInfoNodes[0].querySelectorAll(':scope > span');
          artistNodes.forEach((v) => {
            artistNames.push(v.querySelector('a').innerText);
          });
          trackObj.artists = artistNames.join(",");

          trackObj.album = trackMetaInfoNodes[2].querySelector(':scope > span > span > a').innerText;

        } else if (trackMetaInfoNodes.length === 4) {
          let artistNodes = trackMetaInfoNodes[1].querySelectorAll(':scope > span');
          artistNodes.forEach((v) => {
            artistNames.push(v.querySelector('a').innerText);
          });
          trackObj.artists = artistNames.join(",");

          trackObj.album = trackMetaInfoNodes[3].querySelector(':scope > span > span > a').innerText;
        }

        trackObj.duration = v.querySelectorAll(":scope > div")[3].querySelector("span").innerText;

        trackArray.push(trackObj);
      });
      copyToClipboard(JSON.stringify(trackArray));

      alert(
        document.querySelector(".cover-art-image.cover-art-image-loaded").style[
        "background-image"
        ]
      );
    };
  }
})();
